package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.FormatFblAdapter;
import flc.ast.bean.FormatBean;
import flc.ast.databinding.ActivityVideoCompressBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.media.MediaMetadataInfo;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkRecycleView;

public class VideoCompressActivity extends BaseAc<ActivityVideoCompressBinding> {

    public static String videoPath;
    private String sizeStr;
    private int width, height, bitrate;
    private long size;
    private FormatFblAdapter fblAdapter;
    private List<FormatBean> fblList = new ArrayList<>();
    private int oldPosition;
    private Dialog myFblDialog;
    private String selFbl;
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };


    @Override
    protected int onCreate() {
        return R.layout.activity_video_compress;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoCompressBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.ivVideoCompressSave.setOnClickListener(this);
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivPlayFull.setOnClickListener(this);
        mDataBinding.tvCompressArg.setOnClickListener(this);
        mDataBinding.sbBitrate.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                long compressSize = size * progress / 100;
                String str = ConvertUtils.byte2FitMemorySize(compressSize, 2);
                mDataBinding.tvVideoSize2.setText(str);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //分辨率
        fblDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart://播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivPlayFull://放大
                PlayActivity.videoUri = videoPath;
                startActivity(PlayActivity.class);
                break;
            case R.id.tvCompressArg://压缩参数
                myFblDialog.show();
                break;
            case R.id.ivVideoCompressSave://保存
                save(width, height, bitrate * mDataBinding.sbBitrate.getProgress() / 100);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        fblAdapter.getItem(oldPosition).setSelect(false);
        fblAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        fblAdapter.getItem(position).setSelect(true);
        fblAdapter.notifyItemChanged(position);
        selFbl = fblAdapter.getItem(oldPosition).getStr2();
        if (selFbl.equals(getString(R.string.fbl_arg1))) {
            width = 1920;
            height = 1080;
        } else if (selFbl.equals(getString(R.string.fbl_arg2))) {
            width = 1280;
            height = 720;
        } else if (selFbl.equals(getString(R.string.fbl_arg3))) {
            width = 640;
            height = 480;
        } else if (selFbl.equals(getString(R.string.fbl_arg4))) {
            width = 480;
            height = 360;
        }
        mDataBinding.tvVideoFbl2.setText(width + "*" + height);
        mDataBinding.tvCompressArg.setText(fblAdapter.getItem(position).getStr() + "  " + fblAdapter.getItem(position).getStr2());
        myFblDialog.dismiss();
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(videoPath)) return;
        size = FileUtils.getFileLength(videoPath);
        sizeStr = ConvertUtils.byte2FitMemorySize(size, 2);
        mDataBinding.tvVideoSize1.setText(sizeStr);
        mDataBinding.tvVideoSize2.setText(sizeStr);
        RxUtil.create(new RxUtil.Callback<MediaMetadataInfo>() {
            @Override
            public void doBackground(ObservableEmitter<MediaMetadataInfo> emitter) {
                MediaMetadataInfo mediaMetadataInfo = MediaUtil.getMediaMetadataInfo(videoPath);
                emitter.onNext(mediaMetadataInfo);
            }

            @Override
            public void accept(MediaMetadataInfo info) {
                if (info != null) {
                    width = info.getWidth();
                    height = info.getHeight();
                    bitrate = info.getBitrate();
                    mDataBinding.tvVideoFbl1.setText(width + "*" + height);
                    mDataBinding.tvVideoFbl2.setText(width + "*" + height);
                }
            }
        });
        videoLength = MediaUtil.getDuration(videoPath);
        //设置播放器
        setPlayer();
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                mDataBinding.videoView.seekTo(1);
                stopTime();
            }
        });
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    //压缩视频
    private void save(int width, int height, int bitrate) {
        EditorHolder.editor().videoCompress(videoPath, width, height, bitrate, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.save_success));
                FileP2pUtil.copyPrivateVideoToPublic(mContext, outFilePath);
                startActivity(HomeActivity.class);
            }

            @Override
            public void onFailure(String errMsg) {
                ToastUtils.showShort(getString(R.string.video_compress_def));
                dismissDialog();
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.video_compress_ing) + progress + getString(R.string.unit_percent));
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }


    //分辨率
    private void fblDialog() {
        myFblDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_fbl, null);
        myFblDialog.setContentView(inflate);
        myFblDialog.setCancelable(true);
        Window dialogWindow = myFblDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
        fblAdapter = new FormatFblAdapter();
        recycleView.setAdapter(fblAdapter);
        fblList.add(new FormatBean(getString(R.string.fbl_name1), getString(R.string.fbl_arg1), true));
        fblList.add(new FormatBean(getString(R.string.fbl_name2), getString(R.string.fbl_arg2), false));
        fblList.add(new FormatBean(getString(R.string.fbl_name3), getString(R.string.fbl_arg3), false));
        fblList.add(new FormatBean(getString(R.string.fbl_name4), getString(R.string.fbl_arg4), false));
        fblAdapter.setList(fblList);
        fblAdapter.setOnItemClickListener(this);
    }


}